package com.bawei.mvvm.http;

import com.bawei.mvvm.entity.ApiResponse;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import androidx.lifecycle.LiveData;
import retrofit2.CallAdapter;
import retrofit2.Retrofit;

public class LiveDataCallAdapterFactory extends CallAdapter.Factory {

    //returnType：LiveData<ApiResponse<List<Goods>>>
    @Override
    public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
        if (getRawType(returnType) != LiveData.class) {//获得原始数据类型LiveData
            return null;
        }
        //获取第一个泛型类型：ApiResponse<List<Goods>>
        Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
        //获得ApiResponse<List<Goods>>的原始数据类型：ApiResponse
        Type rawType = getRawType(observableType);
        if (rawType != ApiResponse.class) {
            throw new IllegalArgumentException("type must be ApiResponse");
        }
        if (!ParameterizedType.class.isInstance(observableType)) {
            throw new IllegalArgumentException("resource must be Parameterized");
        }
        return new LiveDataCallAdapter<>(observableType);
    }
}